package com.liuwei.spring.cloud.biz.service.redisson;
import com.liuwei.spring.cloud.framework.spring.ApplicationHelper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RDeque;
import org.redisson.api.RedissonClient;

import java.io.Serializable;
import java.util.function.Consumer;

/**
 * @author : ProducerConsumer
 * @version V1.0
 * @date: 2024/5/14 1:32 PM
 * @Description: TODO
 */
@Slf4j
public class ProducerConsumer {

    private RedissonClient getRedissonInstance() {
        return ApplicationHelper.getBean(RedissonClient.class);
    }

    /**
     * Producer 队尾添加任务
     * @return
     */
    private<T extends Serializable> boolean provide(String name, T task){
        RedissonClient redisson = getRedissonInstance();
        RDeque<T> deque = redisson.getDeque(name);
        deque.addLast(task);
        return true;
    }

    /**
     * Consumer 队首消费任务
     * @param name
     * @param consumer
     * @param reconsumeAfterException
     * @return null if empty
     * @param <T>
     */
    private<T extends Serializable> T consume(String name, Consumer<T> consumer,boolean reconsumeAfterException){
        RedissonClient redisson = getRedissonInstance();
        RDeque<T> deque = redisson.getDeque(name);
        T entity = deque.pollFirst();
        try {
            consumer.accept(entity);
        } catch (Exception e) {
            log.info("Exception:{}",e.getMessage(),e);
            if(reconsumeAfterException){
                deque.addLast(entity);
            }
        }
        return entity;
    }
}
